const formatTime = (date, onlyDate) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  if (onlyDate) {
    return `${[year, month, day].map(formatNumber).join("/")}`;
  }

  return `${[year, month, day].map(formatNumber).join("/")} ${[
    hour,
    minute,
    second,
  ]
    .map(formatNumber)
    .join(":")}`;
};

const formatNumber = (n) => {
  n = n.toString();
  return n.padStart(2, 0);
};

const formatCurrency = (str) => {
  str = str.toString();
  if (!str) return; //判空

  //如果没有小数 添加两位小数 '.00'
  if (str.indexOf(".") === -1) {
    str += ".00";
  } else {
    //如果有判断是否小于11
    var decimal = str.split(".");
    if (decimal[1] < 11) {
      str = decimal[0] + "." + (decimal[1] + "0");
    }
  }

  //切割数组
  //以.分隔为数组
  var arr = str.split(".");
  var left = arr[0];
  //取第一项用正则判断，每隔3位加，
  left = left.replace(new RegExp("B(?=(d{3})+$)", "g"), ",");
  return ((left + "." + arr[1]) * 1).toFixed(2);
};

module.exports = {
  formatTime,
  formatCurrency,
};
